package com.orqlog.timedorder.controller;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Controller
@RequestMapping("order")
public class OrderController {
    private final String expiredOrderId = "001";
    private final String normalOrderId = "002";

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @RequestMapping(value = "/pendings", method = RequestMethod.GET)
    public String payOrderList(Model model) {
        // 模拟订单生成之后把订单发送到rabbitmq
        rabbitTemplate.convertAndSend("ex.pay", "pay", expiredOrderId + ": 创建成功");
        rabbitTemplate.convertAndSend("ex.pay", "pay", normalOrderId + ": 创建成功");

        model.addAttribute("expiredOrderId", expiredOrderId);
        model.addAttribute("normalOrderId", normalOrderId);

        return "pending_orders";
    }


    @RequestMapping(value = "/pay", method = RequestMethod.GET)
    public String pay(String orderId, Model model) {
        // 阻塞线程模拟产生超时
        if (orderId.equals(expiredOrderId)) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 从订单队列获取消息
        String nOrder = (String) rabbitTemplate.receiveAndConvert("q.pay");
        String orderStatus = "找不到订单";
        if (nOrder != null) {
            String[] str = nOrder.split(":");
            if (str[0].equals(orderId)) {
                orderStatus = "有效，支付成功！";
            }
        }
        System.out.println(">>> normal order: " + nOrder);

        // 从订单死信队列获取信息
        String eOrder = (String) rabbitTemplate.receiveAndConvert("q.pay.dlx");
        if (eOrder != null) {
            String[] str = eOrder.split(":");
            if (str[0].equals(orderId)) {
                orderStatus ="超时，订单已经自动取消！";
            }
        }
        System.out.println(">>> expired order: " + eOrder);

        model.addAttribute("orderId", orderId);
        model.addAttribute("orderStatus", orderStatus);
        return "pay_result";
    }

}
